 //
//  JSDataModel.m
//  KidReading
//
//  Created by linziyuan on 16/5/10.
//  Copyright © 2016年 刘赞黄Telen. All rights reserved.
//

#import "JSDataProcessing.h"
#import "ConstDefine.h"

typedef void(^PickImgFinishBlock)(UIImage *pickedImg);
typedef void(^PickImgCacelBlock)();

@interface JSRecordManager : NSObject <UIAlertViewDelegate,UINavigationControllerDelegate,UIImagePickerControllerDelegate,UIPopoverControllerDelegate>

@property (nonatomic, strong) TLRecorderMp3 *mp3recoder;
@property (nonatomic, strong) NSString *currentPath;
@property (nonatomic, strong) NSString *uploadPath;
//
@property (nonatomic, copy) PickImgFinishBlock  imgFinishBlock;
@property (nonatomic, copy) PickImgCacelBlock   imgCacelBlock;
@property (nonatomic, strong) UIPopoverController *popoverObj;
//
@property (nonatomic, strong) UIViewController *currentVC;

+ (instancetype)shareInstance;
//
- (void)startRecord:(void(^)(BOOL isLiterallyBegin))startBlock;
- (void)stropRecord;
- (void)deleteCurrentRecord;

@end

@implementation JSRecordManager

static JSRecordManager *recordManager = nil;

+ (instancetype)shareInstance {
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        recordManager = [[JSRecordManager alloc] init];
        recordManager.mp3recoder = [TLRecorderMp3 new];
    });
    return recordManager;
}

/*******   录音   *********/
- (void)startRecord:(void(^)(BOOL isLiterallyBegin))startBlock {
    self.currentPath = nil;
    int micState = [TLRecorderMp3 canMicrophone];
    if (micState == -1) {   //未配制
        [self performSelector:@selector(startRecord:) withObject:startBlock afterDelay:0.1];
        return;
    }
    //
    if (micState == 0) {    //禁用
        //
        [UIAlertView tl_showTitle:@"" message:ReadLocalizedString(@"msgRecSetting") didClick:^(UIAlertView * _Nullable alertView, NSInteger buttonIndex) {
            if(buttonIndex == 1){
                if ([[UIDevice currentDevice].systemVersion floatValue] < 8) {
                    [[UIApplication sharedApplication] openURL:[NSURL URLWithString:@"prefs:root=Privacy&path=MICROPHONE"]];
                }else{
                    [[UIApplication sharedApplication] openURL:[NSURL URLWithString:UIApplicationOpenSettingsURLString]];
                }
            }else {
                if (startBlock) {
                    startBlock(NO);
                }
            }
        } buttonTitles:ReadLocalizedString(@"cancel"),ReadLocalizedString(@"settings"),nil];
    }
    if(micState == 1){  //允许
        if (startBlock) {
            startBlock(YES);
        }
        NSString* relativeFilePath = [NSString stringWithFormat:@"jsRecord_%lld",[self timestampFromNSDate:[NSDate date]]];
        self.currentPath = [self getFullPathWithRelativePath:relativeFilePath];
        self.mp3recoder.filePath = self.currentPath;
        [self.mp3recoder start];
    }
}

- (void)stropRecord {
    [self.mp3recoder stop];
}

- (void)deleteCurrentRecord {
    if (self.currentPath) {
        BOOL isDirectory = NO;
        BOOL isFileExists = NO;
        isFileExists = [[NSFileManager defaultManager] fileExistsAtPath:self.currentPath isDirectory:&isDirectory];
        if (!isDirectory && isFileExists) {
            [[NSFileManager defaultManager] removeItemAtPath:self.currentPath error:nil];
            self.currentPath = nil;
        }else {
            self.currentPath = nil;
        }
    }
}

- (NSString*)getFullPathWithRelativePath:(NSString*)relativePath {
    NSString *cachesDir = [self getJSRcordCacheFilePath];
    NSString* relativeDirPath = [relativePath stringByDeletingLastPathComponent];
    NSString* recordFileDir = [cachesDir stringByAppendingPathComponent:relativeDirPath];
    
    BOOL isDirectory = NO;
    BOOL isFileExists = NO;
    isFileExists = [[NSFileManager defaultManager] fileExistsAtPath:recordFileDir isDirectory:&isDirectory];
    if (!isDirectory && isFileExists) {
        [[NSFileManager defaultManager] removeItemAtPath:recordFileDir error:nil];
    }
    if (!isDirectory || !isFileExists) {
        [[NSFileManager defaultManager] createDirectoryAtPath:recordFileDir withIntermediateDirectories:YES attributes:nil error:NULL];
    }
    return [cachesDir stringByAppendingPathComponent:relativePath];
}

- (NSString*)getJSRcordCacheFilePath {
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES);
    NSString *cachesDir = [[paths objectAtIndex:0] stringByAppendingPathComponent:@"JSRecord"];
    return cachesDir;
}

- (long long)timestampFromNSDate:(NSDate *)date {
    if (date) {
        long long timestamp = [date timeIntervalSince1970];
        return timestamp;
    }
    return 0;
}


/*********  图片上传  ***********/
- (void)pickImgFinnish:(PickImgFinishBlock)finishBlock cancel:(PickImgCacelBlock)cancelBlock currentVC:(UIViewController *)currentVC{
    UIAlertView *alter = [[UIAlertView alloc] initWithTitle:nil message:nil delegate:self cancelButtonTitle:NSLocalizedString(@"cancel", nil) otherButtonTitles:NSLocalizedString(@"regfromphotos", nil), NSLocalizedString(@"regfromcamera", nil), nil];
    self.imgFinishBlock = finishBlock;
    self.imgCacelBlock = cancelBlock;
    self.currentVC = currentVC;
    [alter show];
}

- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex {
    if (buttonIndex == 1) { //相册
        UIImagePickerController *imagePicker = [[UIImagePickerController alloc] init];
        imagePicker.delegate = self;
        imagePicker.allowsEditing = YES;
        imagePicker.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
        if ([DataProcessing shareSingle].deviceType == DevicesTypes_iPad) {
            //[self.img_userAvatar layoutIfNeeded];
            UIPopoverController *popover = [[UIPopoverController alloc] initWithContentViewController:imagePicker];
            popover.delegate = self;
            CGRect fromRect = CGRectMake(100, 150, 300, 300);
            [popover presentPopoverFromRect:fromRect inView:[RootViewController shareLastInstance].navigationController.view permittedArrowDirections:UIPopoverArrowDirectionAny animated:YES];
            self.popoverObj = popover;
        }else {
            if (self.currentVC) {
                [self.currentVC presentViewController:imagePicker animated:YES completion:nil];
            }else {
               [[RootViewController shareLastInstance].navigationController presentViewController:imagePicker animated:YES completion:nil];
            }
        }
    }else if (buttonIndex == 2) { //相机
        UIImagePickerController *imagePicker = [[UIImagePickerController alloc] init];
        imagePicker.delegate = self;
        imagePicker.allowsEditing = YES;
        imagePicker.sourceType = UIImagePickerControllerSourceTypeCamera;
        if (self.currentVC) {
            [self.currentVC presentViewController:imagePicker animated:YES completion:nil];
        }else {
            [[RootViewController shareLastInstance].navigationController presentViewController:imagePicker animated:YES completion:nil];
        }
    }else {
        self.imgCacelBlock();
    }
}

- (void)popoverControllerDidDismissPopover:(UIPopoverController *)popoverController {
    if(self.imgCacelBlock) self.imgCacelBlock();
    self.popoverObj = nil;
}

- (BOOL)popoverControllerShouldDismissPopover:(UIPopoverController *)popoverController {
    return YES;
}


- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info
{
    UIImage *img = nil;
    if ([[info objectForKey:UIImagePickerControllerMediaType] isEqualToString:(__bridge NSString *)kUTTypeImage]) {
        img = [info objectForKey:UIImagePickerControllerEditedImage];
        //[self performSelector:@selector(saveImage:)  withObject:img afterDelay:0.5];
    }
    [picker dismissViewControllerAnimated:YES completion:^{
        self.imgFinishBlock(img);
    }];
}

- (void)imagePickerControllerDidCancel:(UIImagePickerController *)picker {
    [picker dismissViewControllerAnimated:YES completion:^{
        self.imgCacelBlock();
    }];
}

@end


@implementation UIWebView (JSDataProcessing)
ASSOCIATED_BOOL(newWebView, setNewWebView);

@end

@interface JSDataProcessing ()


@end

@implementation JSDataProcessing
#define __SepS0 @"::_0_::"
#define __SepS1 @"::_1_::"
#define __SepS2 @"::_2_::"

+ (BOOL)startURL:(NSString *)url {
    return [JSDataProcessing startURL:url webView:nil currentVC:nil];
}

+ (BOOL)startURL:(NSString *)url webView:(UIWebView *)webView currentVC:(UIViewController *)currentVC{
    
#if __Debug_JSLog
    NSLog(@"start url ----- url:  %@",url);
#endif
    NSArray *components0 = [url componentsSeparatedByString:__SepS0];
    if ([(NSString *)[components0 objectAtIndex:0] isEqualToString:@"localcall"]) {
        if (components0.count > 1) {
            NSString *component1 = [components0 objectAtIndex:1];
            if ([component1 isEqualToString:@"payvip"] && [components0 count] > 2) {
                NSString* json = [components0 objectAtIndex:2];
                NSMutableDictionary* mdict = [NSMutableDictionary dictionaryWithCapacity:0];
                if (json) {
                    NSArray* tempArr = [json componentsSeparatedByString:__SepS1];
                    for (NSString* keyvalue in tempArr) {
                        NSArray* arr = [keyvalue componentsSeparatedByString:__SepS2];
                        if (arr.count == 2) {
                            [mdict setObject:[arr objectAtIndex:1] forKey:[arr objectAtIndex:0]];
                        }
                    }
                }
                NSString *pid = [mdict valueForKey:@"pid"];
                if (pid.length) {
                    [NSObject msgToClassName:@"TLMobStat" menthed:@"logEvent:eventLabel:" refs:@[PP_purchase,pid] needReturnValue:NO];
                }
                [[NSNotificationCenter defaultCenter] postNotificationName:[components0 objectAtIndex:1] object:[PopBaseViewController new] userInfo:mdict];
            }else if ([component1 isEqualToString:@"weixin"] && [components0 count] > 2){
                NSString* json = [components0 objectAtIndex:2];
                NSMutableDictionary* mdict = [NSMutableDictionary dictionaryWithCapacity:0];
                if (json) {
                    NSArray* tempArr = [json componentsSeparatedByString:__SepS1];
                    for (NSString* keyvalue in tempArr) {
                        NSArray* arr = [keyvalue componentsSeparatedByString:__SepS2];
                        if (arr.count == 2) {
                            [mdict setObject:[arr objectAtIndex:1] forKey:[arr objectAtIndex:0]];
                        }
                    }
                }
                //请求服务器下单
                [self getWeChatPayOrderWithPayDict:mdict WebView:webView];
            }else {
                NSArray *component1Arr = [component1 componentsSeparatedByString:__SepS1];
                NSMutableArray *eventArr = [NSMutableArray new];
                [component1Arr enumerateObjectsUsingBlock:^(NSString*  _Nonnull str, NSUInteger idx, BOOL * _Nonnull stop) {
                    NSArray *component2 = [str componentsSeparatedByString:__SepS2];
                    [eventArr addObject:component2];
                }];
                
                [JSDataProcessing dealWithArr:eventArr index:0 webView:webView currentVC:currentVC];
            }
        }
        return YES;
    }
    return NO;
}

+ (void)dealWithArr:(NSArray*)arr index:(NSInteger)index webView:(UIWebView *)webView currentVC:(UIViewController *)currentVC{
    if (index<arr.count) {
        [JSDataProcessing eventWithArray:arr[index] fullarr:arr webView:webView currentVC:currentVC complete:^(BOOL isSuccess) {
            if (isSuccess)[JSDataProcessing dealWithArr:arr index:index+1 webView:webView currentVC:currentVC];
        }];
    }
}


+ (NSString *)quizTitleWithUrl:(NSString *)url {
    NSArray *components0 = [url componentsSeparatedByString:__SepS0];
    if ([(NSString *)[components0 objectAtIndex:0] isEqualToString:@"localcall"]) {
        if (components0.count > 1) {
            NSString *str = [components0 objectAtIndex:1];
            NSArray *component2 = [str componentsSeparatedByString:__SepS2];
            if (component2.count>1 ) {
                NSString *titleNoti = [component2 objectAtIndex:0];
                if ([titleNoti isEqualToString:@"title"]) {
                    NSString *title = [component2 objectAtIndex:1];
                    return title;
                }
            }
        }
    }
    return @"";
}

+ (NSString *)quizRightTitleWithUrl:(NSString *)url {
    NSArray *components0 = [url componentsSeparatedByString:__SepS0];
    if ([(NSString *)[components0 objectAtIndex:0] isEqualToString:@"localcall"]) {
        if (components0.count > 1) {
            NSString *str = [components0 objectAtIndex:1];
            NSArray *component2 = [str componentsSeparatedByString:__SepS2];
            if (component2.count>1 ) {
                NSString *rightNoti = [component2 objectAtIndex:0];
                if ([rightNoti isEqualToString:@"right-title"]) {
                    NSString *rightTitle = [component2 objectAtIndex:1];
                    return rightTitle;
                }
            }
        }
    }
    return @"";
}

+ (void)eventWithArray:(NSArray *)arr fullarr:(NSArray*)fullarr webView:(UIWebView *)webView currentVC:(UIViewController *)currentVC complete:(void(^)(BOOL isSuccess))complete{
    if (arr.count>1) {
        // action
        if ([(NSString *)[arr objectAtIndex:0] isEqualToString:@"action"]) {
            if (arr.count>1) {
                NSString *eventStr = (NSString *)[arr objectAtIndex:1];
                NSInteger currentArrIndex = [fullarr indexOfObject:arr];
                if ([eventStr isEqualToString:@"hurdleBook"]) {
                    NSInteger bookId = [[fullarr[currentArrIndex + 1] lastObject] integerValue];
                    NSInteger hurdleNo = [[fullarr[currentArrIndex + 2] lastObject] integerValue];
                    if (fullarr.count > currentArrIndex + 3) {
                        NSInteger activityId = [[fullarr[currentArrIndex + 3] lastObject] integerValue];
                        [DataProcessing shareSingle].activityId = activityId;
                    }
                    [[RootViewController shareLastInstance] openSingelBookWithBookId:bookId tbBook:nil isClick:YES];
                    [DataProcessing shareSingle].hurdleNo = hurdleNo;
                }
                if ([eventStr isEqualToString:@"openBook"]) {
                    NSInteger bookId = [[fullarr[currentArrIndex + 1] lastObject] integerValue];
                    [[RootViewController shareLastInstance] openSingelBookWithBookId:bookId tbBook:nil isClick:YES];
                }
                if ([eventStr isEqualToString:@"share"]) {
                    NSString * jsRestult = [fullarr[currentArrIndex + 1] lastObject];
                    jsRestult = [jsRestult URLDecodedString];
                    if (jsRestult.length > 0) {
                        NSError *error = nil;
                        NSData *data = [jsRestult dataUsingEncoding:NSUTF8StringEncoding];
                        NSDictionary *dicMessage = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:&error];
                        [[ShareManager shareManager] JSShareWithJSDict:dicMessage ShowView:webView];
                    }
                }
                //localcall::_0_::action::_2_::hideCloseBtn
                if ([eventStr isEqualToString:@"hideCloseBtn"]) {
                    if ([currentVC isKindOfClass:[PopWebViewController class]]) {
                        [PopWebViewController shareLastInstance].closeBtn.hidden = YES;
                    }else if ([currentVC isKindOfClass:[NoNaviWebViewController class]]) {
                        [[NoNaviWebViewController currentWebVCInstance] hideCloseBtn];
                    }
                }
                //login
                if ([eventStr isEqualToString:@"login"]) {
                    [[RootViewController shareLastInstance] yzt_Login:NO complete:complete];
                }
                //close
                if ([eventStr isEqualToString:@"closeWebView"]) {
                    if (currentVC) {
                        if ([currentVC.closeType isEqualToString:@"quiz"]) {
                            [[DBHelper shareInstance] readInfo_Dicts_sendToNet];
                        }
                        if ([currentVC.closeType isEqualToString:CLOSECHILD]) {
                            if ([currentVC isKindOfClass:[PopWebViewController class]]) {
                                [PopWebViewController shareLastInstance].isShowing = NO;
                                [PopWebViewController closePop];
                            }else{
                                [currentVC.view removeFromSuperview];
                                [currentVC willMoveToParentViewController:nil];
                                [currentVC removeFromParentViewController];
                            }
                        }else {
                            if (currentVC.navigationController) {
                                [currentVC.navigationController popViewControllerAnimated:YES];
                            }else {
                                [currentVC dismissViewControllerAnimated:YES completion:nil];
                            }
                        }
                        [DataProcessing do_Main:^{
                            complete(YES);
                        } delay:0.33];
                    }
                }
                if ([eventStr isEqualToString:@"closeCurrent"]) {
                    if (currentVC) {
                        if ([currentVC.closeType isEqualToString:CLOSECHILD]) {
                            //弹屏奖励
                            [[WaWaYaYaRewardManager defaultManager] logRewardEventIsNeedHandle:YES ActCode:ActCode_ClickPop Param:@"normal_101"];
                            if ([currentVC isKindOfClass:[PopWebViewController class]]) {
                                [PopWebViewController shareLastInstance].isShowing = NO;
                                [PopWebViewController closePop];
                            }else{
                                [currentVC.view removeFromSuperview];
                                [currentVC willMoveToParentViewController:nil];
                                [currentVC removeFromParentViewController];
                            }
                        }else {
                            if (currentVC.navigationController) {
                                [currentVC.navigationController popViewControllerAnimated:YES];
                            }else {
                                [currentVC dismissViewControllerAnimated:YES completion:nil];
                            }
                        }
                        CGFloat delay = 0.33;
                        if ([[UIDevice currentDevice].systemVersion floatValue] < 8) {
                            delay = 0.5;
                        }
                        [DataProcessing do_Main:^{
                            complete(YES);
                        } delay:delay];
                    }
                }
                //getuinfo
                if ([eventStr isEqualToString:@"getUinfo"]) {
                    [JSDataProcessing setUinfoCallback:webView];
                }
                //openUserWorks
                if ([eventStr isEqualToString:@"openUserWorks"]) {
                    if (!currentVC) {
                        return;
                    }
                    NSString *title = @"";
                    for (NSArray *subArr in fullarr) {
                        if (subArr.count>1&&[@"title" isEqualToString:subArr.firstObject]) {
                            title = subArr[1];
                            break;
                        }
                    }
//                    MoreBooksViewController* mbvc = [[MoreBooksViewController alloc] init];
//                    mbvc.type = MoreBooks_Type_originSeries;
//                    mbvc.topTitle = title.URLDecodedString;
//                    if (currentVC.navigationController) {
//                        [currentVC.navigationController pushViewController:mbvc animated:YES];
//                    }else {
//                        [currentVC dismissViewControllerAnimated:YES completion:^{
//                            [[RootViewController shareLastInstance].navigationController pushViewController:mbvc animated:YES];
//                        }];
//                    }
                }
                //flushAuthorInfo
                if ([eventStr isEqualToString:@"flushAuthorInfo"]) {
                    //活动吗激活成功奖励
                    [[WaWaYaYaRewardManager defaultManager] logRewardEventIsNeedHandle:NO ActCode:nil Param:nil];
                    [[RootViewController shareLastInstance] load_UinfoAuthority:NO];
                    [DataProcessing do_Main_quick:^{
                       complete(YES);
                    }];
                }
                //flushHome
                if ([eventStr isEqualToString:@"flushHome"]) {
                    [[RootViewController shareLastInstance] cleanLimitedDateAndReflashLibrary];
                    [DataProcessing do_Main_quick:^{
                        complete(YES);
                    }];
                }
                //gotome
                if ([eventStr isEqualToString:@"gotome"]) {
                    NSInteger targetUid = 0;
                    NSInteger tableIndex = 0;
                    for (NSArray *subArr in fullarr) {
                        if ([[subArr objectAtIndex:0] isEqualToString:@"targetUserId"]) {
                            targetUid = [[subArr objectAtIndex:1] integerValue];
                        }
                        if ([[subArr objectAtIndex:0] isEqualToString:@"tableIndex"]) {
                            tableIndex = [[subArr objectAtIndex:1] integerValue];
                        }
                    }
                    
                    if (targetUid) {
                        if (tableIndex) {
                            if (currentVC.navigationController) {
                                //[AboutMeViewController showUserinfoVCWithCurrentVC:currentVC targetId:targetUid selecteIndex:tableIndex isPresent:NO];
                            }else {
                                [currentVC dismissViewControllerAnimated:YES completion:^{
                                   // [AboutMeViewController showUserinfoVCWithCurrentVC:currentVC targetId:targetUid selecteIndex:tableIndex isPresent:YES];
                                }];
                            }
                        }else {
                            if (currentVC.navigationController) {
                               // [AboutMeViewController showUserinfoVCWithCurrentVC:currentVC targetId:targetUid];
                            }else {
                                [currentVC dismissViewControllerAnimated:YES completion:^{
                                    //[AboutMeViewController showUserinfoVCWithCurrentVC:[RootViewController shareLastInstance].navigationController targetId:targetUid isPresent:YES];
                                }];
                            }
                        }
                    }
                }
                //recordingStart
                if ([eventStr isEqualToString:@"recordingStart"]) {
                    NSInteger time = 60;
                    NSString *path = nil;
                    for (NSArray *subArr in fullarr) {
                        if ([[subArr objectAtIndex:0] isEqualToString:@"time"]) {
                            time = [[subArr objectAtIndex:1] integerValue];
                        }
                        if ([[subArr objectAtIndex:0] isEqualToString:@"path"]) {
                            path = [subArr objectAtIndex:1];
                        }
                    }
                    if (path.length) {
                        [[JSRecordManager shareInstance] startRecord:^(BOOL isLiterallyBegin) {
                            if (isLiterallyBegin) {
                                //NSLog(@"---record literally begin---");
                                [DataProcessing do_Async:^{
                                    [[JSRecordManager shareInstance] stropRecord];
                                    [JSDataProcessing uploadRecordWithPath:path webView:webView];
                                } delay:time];
                            }else {
                                [[JSRecordManager shareInstance] stropRecord];
                                [JSDataProcessing uploadRecordWithPath:@"" webView:webView];
                            }
                        }];
                    }
                }
                //recordingStop
                if ([eventStr isEqualToString:@"recordingStop"]) {
                    NSString *path = nil;
                    for (NSArray *subArr in fullarr) {
                        if ([[subArr objectAtIndex:0] isEqualToString:@"path"]) {
                            path = [subArr objectAtIndex:1];
                            break;
                        }
                    }
                    [[JSRecordManager shareInstance] stropRecord];
                    [JSDataProcessing uploadRecordWithPath:path webView:webView];
                }
                
                //uploadPic
                if ([eventStr isEqualToString:@"uploadPic"]) {
                    NSString *path = nil;
                    NSInteger maxSize = 0;
                    for (NSArray *subArr in fullarr) {
                        if ([[subArr objectAtIndex:0] isEqualToString:@"fileName"]) {
                            path = [subArr objectAtIndex:1];
                            //break;
                        }
                        if ([[subArr objectAtIndex:0] isEqualToString:@"maxSize"]) {
                            maxSize = [[subArr objectAtIndex:1] integerValue];
                        }
                    }
                    
                    if (path.length) {
                        if (![path hasSuffix:@".png"] && ![path hasSuffix:@".jpg"]) {
                            path = [NSString stringWithFormat:@"%@.png",path];
                        }
                        UIViewController *imgPicVC = nil;
                        if (!currentVC.navigationController) {
                            imgPicVC = currentVC;
                        }
                        [[JSRecordManager shareInstance] pickImgFinnish:^(UIImage *pickedImg) {
                            [JSDataProcessing upLoadImgWithPath:path img:pickedImg maxSize:maxSize webView:webView];
                        } cancel:^{
                            [JSDataProcessing cancelPicImgWithWebView:webView];
                        } currentVC:imgPicVC];
                    }
                }
                //excite
                if ([eventStr isEqualToString:@"excite"]) {
                    [JSDataProcessing exciteEventfullarr:fullarr webView:webView currentVC:currentVC complete:complete];
                }
                //target
                if ([eventStr isEqualToString:@"target"]) {
                    if (fullarr.count>1) {
                        NSString *webType = nil;
                        NSString *url = nil;
                        for (NSArray *subArr in fullarr) {
                            if ([subArr[0] isEqualToString:@"browserType"]) {
                                webType = subArr[1];
                            }
                            if ([subArr[0] isEqualToString:@"url"]) {
                                url = [subArr objectAtIndex:1];
                            }
                        }
                        if (url.length) {
                            url = [NetRequest netFullUrl_Get:url fromDict:[[NetRequestWithCache_JR shareSingle] netRequestAddBaseInfo:nil]];
                            if ([webType isEqualToString:@"simple"]) {
                                NoNaviWebViewController *noWebVC = [[NoNaviWebViewController alloc] init];
                                noWebVC.url = url;
                                noWebVC.showType = SettingShowType_H5;
                                noWebVC.clear_Bg = YES;
                                noWebVC.statisticType = StatisticType_none;
                                noWebVC.isfullScrean = YES;
                                [[RootViewController shareLastInstance].navigationController  pushViewController:noWebVC animated:YES];
                            }else {
                                WebViewController *webVC = [[WebViewController alloc] init];
                                webVC.showType = SettingShowType_H5;
                                webVC.url = url;
                                webVC.isfullScrean = YES;
                                [[RootViewController shareLastInstance].navigationController pushViewController:webVC animated:YES];
                            }
                        }
                    }
                }
                //refreshPreView
                if ([eventStr isEqualToString:@"refreshPreView"]) {
                    [BaseVCManager localcallPreRefresh];
                }
                //upgrade
                if ([eventStr  isEqualToString:@"upgrade"]) {
                   // [[UpdateAppRemind defaultInstance] goUpdateApp];
                }
                //statistics
                if ([eventStr isEqualToString:@"statistics"]) {
                    if (fullarr.count>1) {
                        NSString *positionStr = nil;
                        NSString *desStr = nil;
                        for (NSArray *subArr in fullarr) {
                            NSString *keystr = subArr[0];
                            if ([keystr isEqualToString:@"position"]) {
                                positionStr = [subArr objectAtIndex:1];
                            }else if ([keystr isEqualToString:@"desc"]) {
                                desStr = [subArr objectAtIndex:1];
                            }
                        }
                        if (positionStr.length && desStr.length) {
                            positionStr = [positionStr URLDecodedString];
                            desStr = [desStr URLDecodedString];
                            [NSObject msgToClassName:@"TLMobStat" menthed:@"logEvent:eventLabel:" refs:@[positionStr,desStr] needReturnValue:NO];
                        }
                    }
                }
            }
        }
        //link
        if ([(NSString *)[arr objectAtIndex:0] isEqualToString:@"link"]) {
            if (arr.count>1) {
                NSString *url = [arr objectAtIndex:1];
                url = [NetRequest netFullUrl_Get:url fromDict:[[NetRequestWithCache_JR shareSingle] netRequestAddBaseInfo:nil]];
                NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:url]];
                webView.newWebView = YES;
                [webView loadRequest:request];
            }
        }
        //target
        if ([(NSString *)[arr objectAtIndex:0] isEqualToString:@"target"]) {
            if (arr.count>1) {
                NSString *url = [arr objectAtIndex:1];
                url = [NetRequest netFullUrl_Get:url fromDict:[[NetRequestWithCache_JR shareSingle] netRequestAddBaseInfo:nil]];
                NSString *webType = nil;
                for (NSArray *subArr in fullarr) {
                    if ([subArr[0] isEqualToString:@"browserType"]) {
                        webType = subArr[1];
                    }
                }
                if ([webType isEqualToString:@"simple"]) {
                    NoNaviWebViewController *noWebVC = [[NoNaviWebViewController alloc] init];
                    noWebVC.url = url;
                    noWebVC.showType = SettingShowType_H5;
                    noWebVC.clear_Bg = YES;
                    noWebVC.statisticType = StatisticType_none;
                    noWebVC.isfullScrean = YES;
                    [[RootViewController shareLastInstance].navigationController  pushViewController:noWebVC animated:YES];
                }else {
                    WebViewController *webVC = [[WebViewController alloc] init];
                    webVC.showType = SettingShowType_H5;
                    webVC.url = url;
                    webVC.isfullScrean = YES;
                    [[RootViewController shareLastInstance].navigationController pushViewController:webVC animated:YES];
                }
            }
        }
        //jump
        if ([(NSString*)[arr objectAtIndex:0] isEqualToString:@"jump"]) {
            if (arr.count>1) {
                NSString *jumpType = [arr objectAtIndex:1];
                [[RootViewController shareLastInstance] changeToToolBarType:jumpType];
                CGFloat delay = 0.33;
                if ([[UIDevice currentDevice].systemVersion floatValue] < 8) {
                    delay = 0.5;
                }
                [DataProcessing do_Main:^{
                    complete(YES);
                } delay:delay];
            }
        }
    }
}


/** excite */
+ (void)exciteEventfullarr:(NSArray*)fullarr webView:(UIWebView *)webView currentVC:(UIViewController *)currentVC complete:(void(^)(BOOL isSuccess))complete {
    NSMutableDictionary *dict = [NSMutableDictionary dictionary];
    for (NSArray *subArr in fullarr) {
        if (subArr.count >= 2) {
            NSString *keyStr = (NSString *)subArr.firstObject;
            NSString *valueStr = (NSString *)subArr[1];
            if ([keyStr isEqualToString:@"mode"]) {
                [dict setValue:valueStr forKey:@"mode"];
            }
            if ([keyStr isEqualToString:@"itemType"]) {
                [dict setValue:valueStr forKey:@"itemType"];
            }
            if ([keyStr isEqualToString:@"itemVal"]) {
                [dict setValue:valueStr forKey:@"itemVal"];
            }
            if ([keyStr isEqualToString:@"title"]) {
                [dict setValue:valueStr forKey:@"title"];
            }
        }
    }
    if ([[dict valueForKey:@"itemType"] isEqualToString:@"innerUrl"]) { //应用内打开
        NSString *url = [dict valueForKey:@"itemVal"];
        url = [NetRequest netFullUrl_Get:url fromDict:[[NetRequestWithCache_JR shareSingle] netRequestAddBaseInfo:nil]];
        NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:url]];
        webView.newWebView = YES;
        [webView loadRequest:request];
        return;
    }else if ([[dict valueForKey:@"itemType"] isEqualToString:@"outerUrl"]) {   //应用外打开
        NSString *url = [dict valueForKey:@"itemVal"];
        if (url.length && ![url isKindOfClass:[NSNull class]]) {
            [[UIApplication sharedApplication] openURL:[NSURL URLWithString:url]];
        }
        return;
    }
    
    //NSLog(@"excite dict --%@",dict);
//    MoreBooksViewController* mbvc = [[MoreBooksViewController alloc] init];
//    mbvc.type = MoreBooks_Type_selfDefine;
//    mbvc.itemPara = dict;
//    NSString *titleStr = [dict valueForKey:@"title"];
//    mbvc.topTitle = titleStr.URLDecodedString;
//    if ([[dict valueForKey:@"mode"] isEqualToString:@"list"]) {
//        mbvc.showType = MoreShowType_List;
//    }else if ([[dict valueForKey:@"mode"] isEqualToString:@"more"]) {
//        mbvc.showType = MoreShowType_More;
//    }
//    //mbvc.topTitle = title.URLDecodedString;
//    if (currentVC.navigationController) {
//        [currentVC.navigationController pushViewController:mbvc animated:YES];
//    }else {
//        [currentVC dismissViewControllerAnimated:YES completion:^{
//            [[RootViewController shareLastInstance].navigationController pushViewController:mbvc animated:YES];
//        }];
//    }
}
#pragma mark - 微信支付
/*
 *请求微信支付下单接口
 */
+(void)getWeChatPayOrderWithPayDict:(NSDictionary*)payDict WebView:(UIWebView*)webView{
//    if (![WXApi isWXAppInstalled]) {
//        //调用webView弹出信息
//        NSString * strJS = [NSString stringWithFormat:@"alertNoWechat()"];
//        [webView stringByEvaluatingJavaScriptFromString:strJS];
//        return;
//    }
//    [[NetGetPostsWithCache shareInstance] weChatPayOrderWithParams:payDict Success:^(NSDictionary *retDict) {
//        if (retDict[@"prepay_id"]) {
//            [YSWeChatPayHandler jumpToWeChatPayWithPrePay_Id:retDict[@"prepay_id"]];
//            [YSWeChatPayHandler defaultHandler].payReturnBlock = ^(NSInteger returnCode) {
//                switch (returnCode) {
//                    case WXSuccess:
//                    {
//                        //NSLog(@"------------WXPay_Success");
//                        NSString * strJS_success = [NSString stringWithFormat:@"openPaymentResultPage()"];
//                        [webView stringByEvaluatingJavaScriptFromString:strJS_success];
//                    }
//                        break;
//                    case WXErrCodeCommon:
//                    {
//                        //NSLog(@"------------WXPay_Failure");
//                        NSString * strJS_failure = [NSString stringWithFormat:@"openPaymentResultPage()"];
//                        [webView stringByEvaluatingJavaScriptFromString:strJS_failure];
//                    }
//                        break;
//                    case WXErrCodeUserCancel:
//                    {
//                        //NSLog(@"------------WXPay_Cancel");
//                        NSString * strJS_cancel = [NSString stringWithFormat:@"openPaymentButton()"];
//                        [webView stringByEvaluatingJavaScriptFromString:strJS_cancel];
//                    }
//                        break;
//                        
//                    default:
//                        break;
//                }
//            };
//        }
//    } Failure:^(NSError *error) {
//        [[WaitingShow shareSingleShow] showString:NSLocalizedString(@"publishNetFailuer", "") andAutoHide:YES];
//    }];
}

/**上传图片文件*/
+ (void)upLoadImgWithPath:(NSString *)path img:(UIImage *)img maxSize:(NSInteger)maxSize webView:(UIWebView *)webView{
    if (path.length && img) {
        NSData *imgData = UIImagePNGRepresentation(img);
        //NSLog(@"origin image data ------%lu",(unsigned long)imgData.length);
        CGFloat imgDataLength  = imgData.length/(1024.0*1024.0);
        if (maxSize && imgDataLength >= maxSize) {
            CGFloat rate = (CGFloat)imgDataLength/(CGFloat)maxSize;
            CGFloat finalW = img.size.width/rate;
            CGFloat finalH = img.size.height/rate;
            img = [img scaleToSize:CGSizeMake(finalW, finalH)];
            //NSLog(@"final image data ------%lu",(unsigned long)UIImagePNGRepresentation(img).length);
        }
        UpYun *uy = [[UpYun alloc] init];
        uy.successBlocker = ^(NSURLResponse *response, id responseData) {
//            [DataProcess do_Main_quick:^{
//                UIImageView *imgView = [[UIImageView alloc] initWithFrame:CGRectZero];
//                imgView.image = img;
//                CGFloat mvW = img.size.width;
//                CGFloat mvH = img.size.height;
//                if (mvW > 300) {
//                    mvW = 300;
//                    mvH = img.size.height* 300/img.size.width;
//                }else if (mvH > 500) {
//                    mvH = 500;
//                    mvW = img.size.width * 500 /img.size.height;
//                }
//                imgView.frame = CGRectMake(30, 80, mvW, mvH);
//                [webView addSubview:imgView];
//            }];
            NSDictionary *dict = (NSDictionary *)responseData;
            NSString *url = [dict valueForKey:@"url"];
            NSString * strJS = [NSString stringWithFormat:@"_actionObj.setPicToH5('%@')",url];
            NSString * jsRestult = [webView stringByEvaluatingJavaScriptFromString:strJS];
            if (jsRestult.length > 0) {
#if __Debug_JSLog
                NSLog(@"jsRestult------ : %@",jsRestult);
#endif
            }
        };
        uy.failBlocker = ^(NSError *error) {
            [JSDataProcessing cancelPicImgWithWebView:webView];
        };
        [uy uploadFile:img saveKey:path];
    }
}
 
/**取消上传图片*/
+ (void)cancelPicImgWithWebView:(UIWebView *)webView {
    NSString * strJS = [NSString stringWithFormat:@"hideProgress()"];
    NSString * jsRestult = [webView stringByEvaluatingJavaScriptFromString:strJS];
    if (jsRestult.length > 0) {
#if __Debug_JSLog
        NSLog(@"jsRestult------ : %@",jsRestult);
#endif
    }
}


/**上传录音文件*/
+ (void)uploadRecordWithPath:(NSString *)path webView:(UIWebView *)webView{
    if (path.length && [JSRecordManager shareInstance].currentPath.length) {
        UpYun *uy = [[UpYun alloc] init];
        NSData *recordData = [NSData dataWithContentsOfFile:[JSRecordManager shareInstance].currentPath];
        //http://hzjaikan.b0.upaiyun.com
        if (recordData) {
            uy.successBlocker = ^(NSURLResponse *response, id responseData) {
                NSDictionary *dict = (NSDictionary *)responseData;
                NSString *url = [dict valueForKey:@"url"];
                //NSLog(@"url-----%@",url);
                [[JSRecordManager shareInstance] deleteCurrentRecord];
                [JSDataProcessing passUpLoadUrlToWebView:webView url:url];
            };
            uy.failBlocker = ^(NSError *error) {
                [[JSRecordManager shareInstance] deleteCurrentRecord];
                //NSLog(@"--record upload error---%@",error);
                [JSDataProcessing passUpLoadUrlToWebView:webView url:@""];
            };
            [uy uploadFile:recordData saveKey:path];
        }
    }else {
         [JSDataProcessing passUpLoadUrlToWebView:webView url:@""];
    }
}

/**把录音路径给服务器*/
+ (void)passUpLoadUrlToWebView:(UIWebView *)webView url:(NSString *)url{
    if (webView && url.length) {
        [DataProcessing do_Main_quick:^{
            NSString * strJS = [NSString stringWithFormat:@"_actionObj.setRecordingUri('%@')",url];
            NSString * jsRestult = [webView stringByEvaluatingJavaScriptFromString:strJS];
            if (jsRestult.length > 0) {
#if __Debug_JSLog
                NSLog(@"jsRestult------ : %@",jsRestult);
#endif
            }
        }];
    }
}

/**获取右上角按钮信息*/
+ (NSDictionary *)titleBarRightInfo:(UIWebView*)webView {
    NSMutableDictionary *dic = nil;
    NSString * strJS = @"_actionObj.titleBarRight()";
    NSString * jsRestult = [webView stringByEvaluatingJavaScriptFromString:strJS];
    if (jsRestult.length > 0) {
        NSError *error = nil;
        NSData *data = [jsRestult dataUsingEncoding:NSUTF8StringEncoding];
        NSDictionary *dicMessage = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:&error];
        if (error) {
            NSLog(@"H5 返回错误:%@",error);
        }
        dic = [NSMutableDictionary dictionaryWithDictionary:dicMessage];
    }
    return dic;
}


/**注入用户信息*/
+ (void)setUinfoCallback:(UIWebView *)webview {
    NSMutableDictionary *infoDic = [[NetRequestWithCache_JR shareSingle] netRequestAddBaseInfo:nil];
    NSError *error = nil;
    NSData *jsonData = [NSJSONSerialization dataWithJSONObject:infoDic options:NSJSONWritingPrettyPrinted error:&error];
    NSString *jsonString = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
    if (error) {
        NSLog(@"参数转换错误:%@",error);
    }
    NSString * strJS = [NSString stringWithFormat:@"_actionObj.getUinfoCallback(%@)",jsonString];
    NSString * jsRestult = [webview stringByEvaluatingJavaScriptFromString:strJS];
    if (jsRestult.length > 0) {
#if __Debug_JSLog
        NSLog(@"jsRestult------ : %@",jsRestult);
#endif
    }
}

+ (void)reg_poptool_js:(UIWebView *)webView
{
    NSString *filePath = [[NSBundle mainBundle] pathForResource:@"poptool" ofType:@"js"];
    NSString *jsString = [[NSString alloc] initWithContentsOfFile:filePath encoding:NSUTF8StringEncoding error:nil];
    if (jsString) {
        [webView stringByEvaluatingJavaScriptFromString:jsString];
    }else{
        NSLog(@"poptool.js Error");
    }
}

+ (void)js_poptool_clean_device_width:(UIWebView *)webView
{
    NSString * strJS = @"clean_device_width()";
    NSString * jsRestult = [webView stringByEvaluatingJavaScriptFromString:strJS];
    if ([@"true" isEqualToString:jsRestult]) {
        strJS = @"update_tag_attr_src(\"meta\",\"content\",\"\",\"width=50%\")";
        jsRestult = [webView stringByEvaluatingJavaScriptFromString:strJS];
    }
}


+ (void)cancelAllLocalActions {
    [[JSRecordManager shareInstance] stropRecord];
    [[JSRecordManager shareInstance] deleteCurrentRecord];
}

@end
